let urlUtil = {}
/**
 * 解析url
 * @param  {[type]} url [description]
 * @return {[type]}     [description]
 */
urlUtil.parseURL = function(url) {
  let a = document.createElement('a')
  a.href = url
  let params = (function() {
    let ret = {}
    let seg = a.search.replace(/^\?/, '').split('&')
    let len = seg.length
    let i = 0
    for (; i < len; i++) {
      if (!seg[i]) {
        continue
      }
      let index = seg[i].indexOf('=')
      let key = seg[i].substring(0, index)
      let val = seg[i].substring(index + 1)
      ret[key] = encodeURI(val)
    }
    return ret
  })()
  return {
    source: url,
    protocol: a.protocol.replace(':', ''),
    host: a.hostname,
    port: a.port,
    query: this.json2query(params),
    params: params,
    queryObj: (function() {
      let ret = {}
      let seg = (a.hash.split('?')[1] && a.hash.split('?')[1].split('&')) || []
      let len = seg.length
      let i = 0
      for (; i < len; i++) {
        if (!seg[i]) {
          continue
        }
        let index = seg[i].indexOf('=')
        let key = seg[i].substring(0, index)
        let val = seg[i].substring(index + 1)
        ret[key] = val
      }
      return ret
    })(),
    file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
    hash: a.hash.replace('#', ''),
    path: a.pathname.replace(/^([^\/])/, '/$1'),
    relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
    segments: a.pathname.replace(/^\//, '').split('/')
  }
}
urlUtil.json2query = function(obj) {
  let queryStr = '',
    keys
  if (obj && typeof obj === 'object') {
    keys = Object.keys(obj)
    if (keys.length > 0) {
      queryStr = keys
        .map(key => {
          if (!key || key === 'null' || key === 'undefined') {
            return ''
          }
          if (obj[key] !== 'null' && obj[key] !== 'undefined') {
            if (obj[key] || obj[key] === 0) {
              return `${key}=${obj[key]}`
            }
          }
        })
        .join('&')
    }
    queryStr = queryStr.replace(/[\&]+/g, ' ').trim()
    queryStr = queryStr.replace(/[ ]+/g, '&')
    queryStr = (queryStr.length > 0 ? '?' : '') + queryStr
  }
  return queryStr
}

// 站内链接作为外链 按业务需求格式化
urlUtil.outLinkParse = function(link) {
  if (typeof link !== 'string') {
    return ''
  }
  let aElem = document.createElement('a')
  aElem.href = link

  // 添加业务参数
  let addParams = {
    // newWx: newWx? 1: null // 是否为新铂涛微信公众号
  }
  let parseUrlObj = urlUtil.parseURL(link)
  addParams = Object.assign({}, parseUrlObj.params, addParams)
  aElem.search = urlUtil.json2query(addParams)

  let url = aElem.toString()

  // 清除多余参数
  let ticketRule = new RegExp(`&?ticket=[\\w-%]+`, 'gi')
  url = url.replace(ticketRule, '')
  return url
}

export const urlHandler = urlUtil
export default urlHandler
